#include <stdio.h>
#include <unistd.h>
#include "mpi.h"

/**************************************************************
 * \file test_sendrecv.c
 * \author James Edmondson
 * \brief Tests MPI_Sendrecv between rank 0 and all other processes
 *        COMM_WORLD. The test starts and should finish with an
 *        array containing [4,8]. Root always changes the second
 *        value to -1 and receives an 8 from all other nodes to fill
 *        in the second entry. Each other process changes the first
 *        value to -1 and receives a 4 from root to fill in the first
 *        entry. Consequently, all nodes should print [4,8].
 *
 *        For some odd reason, the test is completing sometimes and
 *        sometimes it is causing a collective abort. I'm not entirely
 *        sure why this is happening.
 **************************************************************/

int
main(int argc, char **argv)
{
	int size, rank, i;
	int success = 1;

	int myint[2] = {4,8};
	
	MPI_Init(&argc, &argv);
	
	MPI_Comm_size(MPI_COMM_WORLD, &size);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);

	printf("Size %d, Rank %d\n",size,rank);
	
	if( rank == 0 )
	{
		for( i = 1; i < size; i++ )
		{
			myint[1] = -1;
			MPI_Sendrecv(&myint[0],1,MPI_INT,i,10,
					&myint[1],1,MPI_INT,i,10,
					MPI_COMM_WORLD,MPI_STATUS_IGNORE);
			printf("RECV: myint[0]: %d myint[1]: %d\n",myint[0], myint[1]);
			success = success && (myint[0] == 4);
			success = success && (myint[1] == 8);
		}
		if (success == 1) {
			printf("SUCCESS\n");
		}
	}
	else 
	{
		myint[0] = -1;
		MPI_Sendrecv(&myint[1],1,MPI_INT,0,10,
					&myint[0],1,MPI_INT,0,10,
					MPI_COMM_WORLD,MPI_STATUS_IGNORE);
		printf("SEND: myint[0]: %d myint[1]: %d\n", myint[0], myint[1]);
	}
	
	
	MPI_Finalize();
	return 0;
}

